/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-roadSOS
*
* @File name : RoadSosController.java
*
* @Author : Administrator
*
* @Date : 2017年5月12日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年5月12日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.roadSOS.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.infoservice.filestore.FileStore;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import org.marketing.common.Response;
import com.yonyou.gmmc.service.roadSOS.constant.RoadSOSConstant;
import com.yonyou.gmmc.service.roadSOS.model.TtSoshelp;
import com.yonyou.gmmc.service.roadSOS.service.RoadSosService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author Administrator
 * @date 2017年5月12日
 */
@RestController
@RequestMapping(value = RoadSOSConstant.BASE_PATH + "/" + RoadSOSConstant.VERSION)
@Api("道路救援")
public class RoadSosController {

	private Logger logger = Logger.getLogger(RoadSosController.class);

	@Autowired
	private RoadSosService roadSosService;

	/**
	 * 提交道路救援
	 * 
	 * @author Administrator
	 * @date 2017年5月12日
	 * @param ttSoshelp
	 * @return
	 */
	@RequestMapping(value = "/roadsideAssistance", method = RequestMethod.POST)
	@ApiOperation(value = "提交道路救援", notes = "提交道路救援")
	@ResponseBody
	public Response<Map<String, Object>> roadsideAssistance(@RequestBody TtSoshelp ttSoshelp,
			HttpServletRequest request,
			@RequestParam(value = "userId_", required = false, defaultValue = "") String userId_) {
		Map<String, Object> resultMap = new HashMap<>();
		String userId = "";
		try {
			if (!CheckUtil.NullOrEmpty(userId_)) {
				userId = userId_;
			} else {
				userId = request.getHeader(CommonConstant.HEAD_USER_ID);
			}
			resultMap = roadSosService.roadsideAssistance(ttSoshelp, userId);
			logger.info("返回结果为>>>>>>>>>>>>>>" + resultMap);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, resultMap, "");
		} catch (Exception e) {
			logger.error("保存状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 道路救援可选销售店
	 * 
	 * @author Administrator
	 * @date 2017年5月12日
	 * @param ttSoshelp
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/nearDealer", method = RequestMethod.POST)
	@ApiOperation(value = "道路救援可选销售店", notes = "道路救援可选销售店")
	@ResponseBody
	public Response<Map<String, Object>> getDealer(@RequestBody TtSoshelp ttSoshelp, HttpServletRequest request,
			@RequestParam(value = "userId_", required = false, defaultValue = "") String userId_) {
		Map<String, Object> result = new HashMap<>();
		String userId = "";
		try {
			if (!CheckUtil.NullOrEmpty(userId_)) {
				userId = userId_;
			} else {
				userId = request.getHeader(CommonConstant.HEAD_USER_ID);
			}
			ttSoshelp.setCarOwnerUserId(Long.valueOf(userId));
			result = roadSosService.getDealer(ttSoshelp);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 更新救援状态
	 * 
	 * @author Administrator
	 * @date 2017年6月5日
	 * @param ttSoshelp
	 * @return
	 */
	@RequestMapping(value = "/sosStatus", method = RequestMethod.POST)
	@ApiOperation(value = "更新救援状态", notes = "更新救援状态")
	@ResponseBody
	public Response<Map<String, Object>> updateStatus(@RequestBody TtSoshelp ttSoshelp) {
		Map<String, Object> result = new HashMap<>();
		try {
			result = roadSosService.updateStatus(ttSoshelp);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * PC-道路救援查询
	 * 
	 * @author Administrator
	 * @date 2017年6月5日
	 * @param ttSoshelp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/sosList", method = RequestMethod.GET)
	@ApiOperation(value = "PC-道路救援查询", notes = "PC-道路救援查询")
	public Response<PageInfo<TtSoshelp>> roadSosList(
			@RequestParam(required = false, defaultValue = "10") Integer pageNum,
			@RequestParam(required = false, defaultValue = "10") String pageSize,
			@RequestParam(required = false, defaultValue = "") String dealerCode // 经销商编码
			, @RequestParam(required = false, defaultValue = "") String oddNumber // 救援单号
			, @RequestParam(required = false, defaultValue = "") String userName // 车主姓名
			, @RequestParam(required = false, defaultValue = "") String phone // 联系电话
			, @RequestParam(required = false, defaultValue = "") String licenseNo // 车牌号码
			, @RequestParam(required = false, defaultValue = "") Integer status // 救援状态
			, @RequestParam(required = false, defaultValue = "") String supportDate_start // 请求时间
																							// -开始
			, @RequestParam(required = false, defaultValue = "") String supportDate_end // 请求时间
																						// -结束
			, @RequestParam(required = false, defaultValue = "") String supportFinishDate_start // 救援完成时间-开始
			, @RequestParam(required = false, defaultValue = "") String supportFinishDate_end // 救援完成时间
																								// -结束
			, @RequestParam(required = false, defaultValue = "") String sosType // 救援方式
			, @RequestParam(required = false, defaultValue = "") String userId // 救援方式
	) {
		logger.info("用户》》》》》" + userId);
		try {
			if (userId.equals("1")) {
				logger.info("厂商账号，不需要查DealerCode");
				dealerCode = "";
			} else {
				logger.info("经销商账号，根据userId去查DealerCode");
				dealerCode = roadSosService.selectDealerByUserId(userId);
			}
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("pageNum", pageNum);
			paramMap.put("pageSize", pageSize);
			paramMap.put("dealerCode", dealerCode);
			paramMap.put("oddNumber", oddNumber);
			paramMap.put("userName", userName);
			paramMap.put("phone", phone);
			paramMap.put("licenseNo", licenseNo);
			paramMap.put("status", status);
			paramMap.put("supportDate_start", supportDate_start);
			paramMap.put("supportDate_end", supportDate_end);
			paramMap.put("supportFinishDate_start", supportFinishDate_start);
			paramMap.put("supportFinishDate_end", supportFinishDate_end);
			paramMap.put("sosType", sosType);
			PageInfo<TtSoshelp> result = roadSosService.roadSosList(paramMap);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * PC-道路救援查询条件列表
	 * 
	 * @author Administrator
	 * @date 2017年6月6日
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/conditionList", method = RequestMethod.GET)
	@ApiOperation(value = "PC-查询条件", notes = "PC-查询条件")
	public Response<Map<String, Object>> selectList() {
		Map<String, Object> result = new HashMap<>();
		try {
			result = roadSosService.selectList();
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * PC-树形经销商
	 * 
	 * @author Administrator
	 * @date 2017年6月14日
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/dealerTree", method = RequestMethod.GET)
	@ApiOperation(value = "PC-树形经销商", notes = "PC-树形经销商")
	public Response<List<Map<String, Object>>> selectDealer() {
		List<Map<String, Object>> result = new ArrayList<>();
		try {
			result = roadSosService.selectDealer();
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * PC-道路救援导出
	 * 
	 * @author Administrator
	 * @date 2017年6月14日
	 * @param pageNum
	 * @param pageSize
	 * @param dealerCode
	 * @param oddNumber
	 * @param userName
	 * @param phone
	 * @param licenseNo
	 * @param status
	 * @param supportDate_start
	 * @param supportDate_end
	 * @param supportFinishDate_start
	 * @param supportFinishDate_end
	 * @param sosType
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/sosExport", method = RequestMethod.GET)
	@ApiOperation(value = "PC-道路救援导出", notes = "PC-道路救援导出")
	public Response<Map<String, String>> sosExport(@RequestParam(required = false, defaultValue = "10") Integer pageNum,
			@RequestParam(required = false, defaultValue = "10") String pageSize,
			@RequestParam(required = false, defaultValue = "") String dealerCode // 经销商编码
			, @RequestParam(required = false, defaultValue = "") String oddNumber // 救援单号
			, @RequestParam(required = false, defaultValue = "") String userName // 车主姓名
			, @RequestParam(required = false, defaultValue = "") String phone // 联系电话
			, @RequestParam(required = false, defaultValue = "") String licenseNo // 车牌号码
			, @RequestParam(required = false, defaultValue = "") Integer status // 救援状态
			, @RequestParam(required = false, defaultValue = "") String supportDate_start // 请求时间
																							// -开始
			, @RequestParam(required = false, defaultValue = "") String supportDate_end // 请求时间
																						// -结束
			, @RequestParam(required = false, defaultValue = "") String supportFinishDate_start // 救援完成时间-开始
			, @RequestParam(required = false, defaultValue = "") String supportFinishDate_end // 救援完成时间
																								// -结束
			, @RequestParam(required = false, defaultValue = "") String sosType // 救援方式
	) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			Map<String, Object> queryMap = new HashMap<String, Object>();
			// queryMap.put("pageNum", pageNum);
			// queryMap.put("pageSize", pageSize);
			queryMap.put("dealerCode", dealerCode);
			queryMap.put("oddNumber", oddNumber);
			queryMap.put("userName", userName);
			queryMap.put("phone", phone);
			queryMap.put("licenseNo", licenseNo);
			queryMap.put("status", status);
			queryMap.put("supportDate_start", supportDate_start);
			queryMap.put("supportDate_end", supportDate_end);
			queryMap.put("supportFinishDate_start", supportFinishDate_start);
			queryMap.put("supportFinishDate_end", supportFinishDate_end);
			queryMap.put("sosType", sosType);
			List<TtSoshelp> sosList = roadSosService.sosExport(queryMap);
			ExportParams params = new ExportParams("道路救援", "道路救援", ExcelType.XSSF);
			logger.info("params为>>>>>>" + params);
			Workbook book = ExcelExportUtil.exportExcel(params, TtSoshelp.class, sosList);
			logger.info("book为>>>>>>" + book);
			book.write(os);
			String fileName = FileStore.getInstance().write("nd02", "fs01", "sosList.xls", os.toByteArray());

			Map<String, String> fileResult = new HashMap<String, String>();
			fileResult.put("fileName", "sosList.xls");
			fileResult.put("url", FileStore.getInstance().getDomainURL(fileName));
			return new Response(ResultMsgConstants.RESULT_CODE_SUCCESS, fileResult, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		} finally {
			try {
				os.close();
			} catch (IOException e) {
			}
		}
	}
}
